﻿CREATE PROCEDURE [dbo].[Program_InsertUpdate]

	@id					BIGINT,

	@name				VARCHAR (0060), 

	@description		VARCHAR (0999),


	@insurerId			BIGINT,

	@programTypeId	BIGINT,

	@uniqueId			VARCHAR (0020) = null,

	@legacyId			VARCHAR (0020),


	@enabled			BIT,

	@modifiedId			VARCHAR (0060)

AS

	BEGIN 

		MERGE Program

			USING (SELECT @id) AS Source (Id)

				ON Program.Id = Source.Id

			WHEN MATCHED THEN 

				UPDATE SET 

					Name = @name,

					Description = @description,

					InsurerId = @insurerId, 

					ProgramTypeId = @programTypeId,

					UniqueId =  ISNULL (@uniqueId, Program.Id),

					LegacyId = @legacyId,

					Enabled = @enabled,

					ModifiedId = @modifiedId,

					ModifiedDateTime = GETDATE ()

			WHEN NOT MATCHED THEN 

				INSERT (Name, Description, InsurerId, ProgramTypeId, UniqueId, LegacyId, Enabled, CreateId, CreateDateTime, ModifiedId, ModifiedDateTime) 

					VALUES (@name, @description, @insurerId, @programTypeId, 
					
						ISNULL (@uniqueId, SUBSTRING (REPLACE (NEWID (), '-', ''), 13, 20)),
						
						@legacyId, @enabled, @modifiedId, GETDATE (), @modifiedId, GETDATE())

		; -- MERGE ( END )
		
		-- FOR NEW INSERTS, NEED TO WAIT UNTIL AFTER INSERT TO SET THE

		-- UNIQUE ID TO THE NEWLY GENERATED IDENTITY OF THE ENTITY

		IF ((@uniqueId IS NULL) AND (ISNULL (@id, 0) = 0))

			UPDATE Program SET UniqueId = Id WHERE Id = @@IDENTITY

	END

	